#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<ctype.h>

//重定向定义
#define NoneRedir -1
#define StdinRedir 0
#define StdoutRedir 1
#define AppendRedir 2

#define StrEnd '\0'
#define IgnSpace(buf,pos) do{while(isspace(buf[pos])) pos++;}while(0)

int redir_type = NoneRedir;
char* filename = NULL;

#define SEP " "
#define SIZE 1024
#define MAX_ARGC 64


char* argv[MAX_ARGC];
char pwd[SIZE];
char env[SIZE];
int lastcode = 0;

const char* HostName()
{
    char * hostname = getenv("HOSTNAME");
    if(hostname) return hostname;
    else return "None";
}

const char* UserName()
{
    char * username = getenv("USER");
    if(username) return username;
    else return "None";
}

const char* CurrentWorkDir()
{
    char * pwd = getenv("PWD");
    if(pwd) return pwd;
    else return "None";
}

int Interactive(char out[],int size)
{
    printf("[%s@%s %s]$ ",UserName(),HostName(),CurrentWorkDir());
    fgets(out,size,stdin);
    out[strlen(out)-1] = 0;
 
    return strlen(out);
}

void CheckRedir(char in[])
{
    //ls -l -a > log.txt
    //ls -l -a >> log.txt
    //cat < log.txt
    int pos = strlen(in)-1;
    while(1)
    {
        if(in[pos] == '>')
        {
            if(in[pos-1] == '>')
            {
                redir_type = AppendRedir;
                in[pos-1] = StrEnd;
                pos++;
                IgnSpace(in,pos);
                filename = in+pos;
                break;
            }
            else{
                redir_type = StdoutRedir;
                in[pos++] = StrEnd;
                IgnSpace(in,pos);
                filename = in+pos;
                break;
            }
        }
        else if(in[pos] == '<')
        {
            redir_type = StdinRedir;
            in[pos++] = StrEnd;
            IgnSpace(in,pos);
            filename = in+pos;
            break;
        }
        else{
            pos--;
        
        }
    }
}

void Split(char in[])
{    
    CheckRedir(in);
    int i = 0;
    argv[i++] = strtok(in,SEP);
    while(argv[i++] = strtok(NULL,SEP));
    if(strcmp("ls",argv[0]) == 0)
    {
        argv[i-1] = (char*)"--color";
        argv[i] = NULL;
    }
}

void Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        int fd = -1;
        if(redir_type == StdinRedir)
        {
            fd = open(filename,O_RDONLY);
            dup2(fd,0);
        }
        else if(redir_type == StdoutRedir )
        {
            fd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
            dup2(fd,1);
        }
        else if(redir_type == AppendRedir)
        {
            fd = open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);
            dup2(fd,1);
        }
        else{
            //do nothing
        }
        execvp(argv[0],argv);
        exit(1);
    }
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid == id)
    {
        lastcode = WEXITSTATUS(status);
    }
}

char* Home()
{
    return getenv("HOME");
}

int BuildinCmd()
{   
    //判断是否是内建命令 是1 否0
    int ret = 0;
    if(strcmp("cd",argv[0]) == 0)
    {
        ret = 1;
        char *target = argv[1];//cd .. /uer/bin
        if(!target) target = Home();
        chdir(target);
        //不为空，获取当前路径，拷贝到temp数组中
        char temp[1024];
        getcwd(temp,1024);
        //将temp即路径以特定的格式存到pwd中，再将其输出到环境变量中
        snprintf(pwd,SIZE,"PWD=%s",temp);
        putenv(pwd);
    }
    else if(strcmp("export",argv[0]) == 0)
    {
        //export myshell=123123
        ret = 1;
        if(argv[1])
        {
            strcpy(env,argv[1]);
            putenv(env);
        }
    }
    else if(strcmp("echo",argv[0]) == 0)
    {
        //echo $?  echo $HOME    echo helloworld
        ret = 1;
        if(argv[1] == NULL)
        {
            printf("\n");
        }
        else{
            if(argv[1][0] == '$')
            {
                if(argv[1][1] == '?')
                {
                    printf("%d\n",lastcode);
                    lastcode = 0;
                }
                else{
                    char * e = getenv(argv[1]+1);
                    if(e)   printf("%s\n",e);
                }
            }
            else{
                printf("%s\n",argv[1]);
            }
        }
    }
    return ret;
}

int main()
{
    while(1)
    {
        char commandline[SIZE];
        //1.输出提示符，并读取字符串
        int n = Interactive(commandline,SIZE);
        if(n == 0) continue;
        //2.切割字符串
        Split(commandline);

        //3.判断内建
        n = BuildinCmd();
        if(n)    continue;
        //4.创建子进程.进程程序切换
        Execute();   
        //int i = 0;
        //for(i = 0;argv[i];i++)
        //{
        //    printf("argv[%d]:%s\n",i,argv[i]);
        //}
        //printf("%s\n",commandline);
    }
    return 0;
}






